package com.mengyan.framework.exception;

import com.google.common.collect.ImmutableMap;
import com.mengyan.framework.model.response.CommonCode;
import com.mengyan.framework.model.response.ResponseResult;
import com.mengyan.framework.model.response.ResultCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

/**
 * Created by mengyan on 2019/2/6.
 */
@Slf4j
public class ExceptionCatchBase {

    private static volatile ImmutableMap<Class<? extends Throwable>, ResultCode> EXCEPTIONS;

    protected static ImmutableMap.Builder<Class<? extends Throwable>, ResultCode> builder = ImmutableMap.builder();

    @ExceptionHandler(CustomException.class)
    @ResponseBody
    //定义返回的状态类型
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public ResponseResult customException(CustomException customException) {
        log.error("catch customException:{}",customException.getMessage());
        ResultCode resultCode = customException.getResultCode();
        return new ResponseResult(resultCode);
    }

    @ExceptionHandler(Exception.class)
    @ResponseBody
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public ResponseResult exception(Exception exception) {
        log.error("catch exception:{}",exception.getMessage());
        if(EXCEPTIONS == null) {
            synchronized (ExceptionCatchBase.class) {
                if(EXCEPTIONS == null) {
                    EXCEPTIONS = builder.build();
                }
            }

        }
        ResultCode resultCode = EXCEPTIONS.get(exception.getClass());
        if(resultCode != null) {
            return new ResponseResult(resultCode);
        }
        return new ResponseResult(CommonCode.SERVER_ERROR);
    }

    static {
        builder.put(HttpMessageNotReadableException.class, CommonCode.INVALID_PARAM);
    }
}
